package bgg4j;



import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import bgg4j.http.HttpClient;

public class Bgg {
    HttpClient http = null;
    private String baseURL = "http://www.boardgamegeek.com/";
    private String m_homedir = null;
    public Bgg() {
        http = new HttpClient();
    }

    public Bgg(String baseURL) {
        this();
        this.baseURL = baseURL;
    }

    public String getBaseURL(){
    	return baseURL;
    }
    
    public void setDir(String path){
    	m_homedir = path;
    }
    
    public final synchronized List<CollectedGame> loadSnapshotCollection(String userid) throws
    BggException {
    	DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    	DocumentBuilder builder;
		try {
			File snapshot = new File(m_homedir + userid + "_collection_snapshot.xml");
			if (!snapshot.exists()){
				this.getSnapShotCollection(userid);
			}
			builder = dbfactory.newDocumentBuilder();
			Document doc = builder.parse(snapshot);
			return CollectedGame.constructCollectedGames(doc, this);
		} catch (Exception e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
			return new ArrayList<CollectedGame>(0);
		}
    }
    
    public final synchronized List<GameInfo> loadSnapshotGameInfo(String userid) throws
    BggException {
    	DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    	DocumentBuilder builder;
		try {
			File snapshot = new File(m_homedir + userid + "_gameinfo_snapshot.xml");
			if (!snapshot.exists()){
				List<CollectedGame> list_collection = this.loadSnapshotCollection(userid);
				StringBuffer strGameID = new StringBuffer();
				for (CollectedGame game : list_collection){
					strGameID.append(game.getGameID() + ",");
				}
				this.getSnapShotGameInfo(userid, strGameID.toString());
			}
			builder = dbfactory.newDocumentBuilder();
			Document doc = builder.parse(new File(m_homedir +userid + "_gameinfo_snapshot.xml"));
			return GameInfo.constructGameInfo(doc, this);
		} catch (Exception e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
			return new ArrayList<GameInfo>(0);
		}
    }
    
    public final synchronized void getFile(String url, String filepath) throws
    BggException, IOException {
    	if (url != null){
    		http.getFile(url, filepath);
    	}
    }
    
    public final synchronized List<QueryResult> getQueryResult(String key, boolean isExact) throws
    BggException{
    	String option = null;
    	if (isExact){
    		option = "&exact=1";
    	}else{
    		option = "";
    	}
    	return QueryResult.constructQueryResult(http.get(baseURL +
    									"xmlapi/search?search=" + key + option).asDocument(), this);
    }
    
    public final synchronized void getSnapShotCollection(String userid) throws
    BggException, IOException {
    	InputStreamReader in = http.get(baseURL + "xmlapi/collection/" + userid).asReader();
    	File file = new File(m_homedir +userid + "_collection_snapshot.xml");
    	//FileWriter fw = new FileWriter(file);
    	FileOutputStream fos = new FileOutputStream(file);
        int ch;
        boolean isFirstChar = true;
        while ((ch = in.read()) != -1) {
        	if (isFirstChar == true && ch == '\n'){
        		isFirstChar = false;
        	}else{
        		fos.write(ch);
        		isFirstChar = false;
        	}
        }
       
        in.close();
        //fw.close();
        fos.flush();
        fos.close();
    }
    
    public final synchronized List<CollectedGame> getCollection(String userid) throws
    BggException {
    return CollectedGame.constructCollectedGames(http.get(baseURL +
                                             "xmlapi/collection/" + userid).
                                    asDocument(), this);
    }
    
    public final synchronized void getSnapShotGameInfo(String userid, String gameID) throws
    BggException, IOException {
    	InputStreamReader in = http.get(baseURL + "xmlapi/game/" + gameID + "?stats=1").asReader();
    	File file = new File(m_homedir +userid + "_gameinfo_snapshot.xml");
    	//FileWriter fw = new FileWriter(file);
    	FileOutputStream fos = new FileOutputStream(file);
        int ch;
        while ((ch = in.read()) != -1) {
            //fw.write(ch);
        	fos.write(ch);
        }
        in.close();
        fos.flush();
        fos.close();
    }
    
    public final synchronized List<GameInfo> getGameInfo(String gameID) throws
    BggException {
    	return GameInfo.constructGameInfo(http.get(baseURL + "xmlapi/game/" + gameID + "?stats=1").asDocument(), this);
    }
}
